/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package com.velocityme.session;

import com.velocityme.entity.ChangeDelta;
import com.velocityme.entity.Status;
import com.velocityme.enums.ChangeDeltaType;
import com.velocityme.enums.Permission;
import java.util.Collection;
import javax.ejb.EJB;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

/**
 *
 * @author rcrida
 */
@Stateless
public class StatusBean implements StatusLocal {
    @EJB
    private NodeLocal nodeBean;

    @PersistenceContext
    private EntityManager em;

    public Status findStatus(KeyLocal key, Long statusId) {
        Status status = em.find(Status.class, statusId);
        key.assertHasPermission(status, Permission.NODE_VIEW);
        return status;
    }

    @Override
    public Collection<Status> findAllStatuses(KeyLocal key) {
        key.validateKey();
        return em.createNamedQuery("findAllStatuses").getResultList();
    }

    public Status createStatus(KeyLocal key, Status status) {
        key.assertHasPermission(status.getParentNode(), Permission.STATUS_CREATE);
        ChangeDelta changeDelta = status.addChangeDelta(ChangeDeltaType.CREATE, key.getUser());
        nodeBean.logCreate(status, changeDelta);
        em.persist(status);
        em.persist(changeDelta);
        return status;
    }

    public void editStatus(KeyLocal key, Status status) {
        Status current = em.find(Status.class, status.getId());
        key.assertHasPermission(status, Permission.STATUS_EDIT);
        ChangeDelta changeDelta = status.addChangeDelta(ChangeDeltaType.EDIT, key.getUser());
        nodeBean.logEdit(status, current, changeDelta);
        em.persist(changeDelta);
        em.merge(status);
    }
    
}
